<!-- 医生接诊 -->
<template>
    <div>
        <el-row>
            <el-col :span="6">
                <el-card :body-style="{ margin: '10px', padding: '5px' }">
                    <el-form ref="patientform" :model="patientform" label-width="80px" label-position="left">
                        <el-form-item label="患者姓名">
                            <el-input v-model="patientform.patientName" disabled>
                                <el-button slot="append" icon="el-icon-s-custom" @click="checkpatient"></el-button>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="身份证号">
                            <el-input v-model="patientform.idCard" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="患者电话">
                            <el-input v-model="patientform.tel" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="性别" prop="gender">
                            <el-radio-group v-model="patientform.gender">
                                <el-radio label="0">女</el-radio>
                                <el-radio label="1">男</el-radio>
                                <el-radio label="2">未知</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="出生日期" prop="patientDate">
                            <el-date-picker clearable v-model="patientform.patientDate" type="date"
                                value-format="yyyy-MM-dd" placeholder="请选择出生日期">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="患者年龄" prop="age">
                            <el-input v-model="patientform.age" placeholder="请输入患者年龄" />
                        </el-form-item>
                        <el-form-item label="地址信息" prop="address">
                            <el-input v-model="patientform.address" placeholder="请输入地址信息" type="textarea" />
                        </el-form-item>
                        <el-form-item label="过敏史" prop="allergy">
                            <el-input v-model="patientform.allergy" placeholder="请输入过敏史" type="textarea" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="update">更新患者信息</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
            <el-col :span="18">
                <el-card>
                    <el-form :inline="true" size="mini">
                        <el-form-item label="挂号编号：">{{
                            registration.registrationNo
                            }}</el-form-item>
                        <el-form-item label="病例编号：">{{
                            treatform.treatNo
                            }}</el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="add">保存病例</el-button>
                            <el-button type="success" @click="updateReg">就诊完成</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
            <el-col :span="18">
                <el-card :body-style="{ margin: '5px', padding: '5px' }">
                    <el-tabs v-model="activeName2" type="border-card">
                        <el-tab-pane label="病例" name="first">
                            <el-form ref="treatform" :model="treatform" label-width="80px" size="mini"
                                label-position="left">
                                <el-form-item label="发病日期" prop="treatDate">
                                    <el-date-picker clearable v-model="treatform.treatDate" type="date"
                                        value-format="yyyy-MM-dd" placeholder="请选择发病日期">
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="是否传染" prop="treatContagion">
                                    <el-select v-model="treatform.treatContagion" placeholder="请选择是否传染" clearable>
                                        <el-option v-for="dict in dict.type.his_treat_contagion" :key="dict.value"
                                            :label="dict.label" :value="dict.value" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="主诉" prop="treatComplaint">
                                    <el-input v-model="treatform.treatComplaint" placeholder="请输入主诉" type="textarea"
                                        maxlength="100" show-word-limit />
                                </el-form-item>
                                <el-form-item label="诊断信息" prop="info">
                                    <el-input v-model="treatform.treatInfo" placeholder="请输入诊断信息" type="textarea"
                                        maxlength="100" show-word-limit />
                                </el-form-item>
                                <el-form-item label="医生建议" prop="treatAdvice">
                                    <el-input v-model="treatform.treatAdvice" placeholder="请输入医生建议" type="textarea"
                                        maxlength="100" show-word-limit />
                                </el-form-item>
                                <el-form-item label="备注" prop="remark">
                                    <el-input v-model="treatform.remark" placeholder="请输入备注" type="textarea"
                                        maxlength="250" show-word-limit />
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>
                        <!-- 必须先保存了病例才能开处方（开药） -->
                        <el-tab-pane v-if="treatform.treatNo !== null" label="处方" name="second">
                            <!-- <el-button type="success" @click="addmedicine">添加用药处方</el-button>
                            <el-button type="success" @click="addcheck">添加检查处方</el-button> -->

                            <!-- 开药单 -->
                            <!-- 操作按键 -->
                            <el-row :gutter="10" class="mb8">
                                <el-col :span="1.5">
                                    <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddP"
                                        v-hasPermi="['his:prescription:add']">新增</el-button>
                                </el-col>
                                <el-col :span="1.5">
                                    <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
                                        @click="handleUpdateP" v-hasPermi="['his:prescription:edit']">修改</el-button>
                                </el-col>
                                <el-col :span="1.5">
                                    <el-button type="danger" plain icon="el-icon-delete" size="mini"
                                        :disabled="multiple" @click="handleDeleteP"
                                        v-hasPermi="['his:prescription:remove']">删除</el-button>
                                </el-col>
                                <el-col :span="1.5">
                                    <el-button type="warning" plain icon="el-icon-download" size="mini"
                                        @click="handleExportP" v-hasPermi="['his:prescription:export']">导出</el-button>
                                </el-col>
                            </el-row>

                            <!-- 开药单表 -->
                            <el-table v-loading="loading" :data="prescriptionList"
                                @selection-change="handleSelectionChange">
                                <el-table-column type="selection" width="55" align="center" />
                                <!-- <el-table-column label="序号" align="center" type="index" :index="indexMethod" /> -->
                                <!-- <el-table-column label="药品名称" align="center" prop="medicineId" /> -->
                                <el-table-column label="药品处方id" align="center" prop="prescriptionId" />
                                <el-table-column label="药品名称" align="center" prop="medicineId">
                                    <template slot-scope="scope">
                                        <span>{{ getMedicineName(scope.row.medicineId) }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="数量" align="center" prop="quantity" />
                                <!-- <el-table-column label="单价" align="center" prop="deptNum" /> -->
                                <el-table-column label="金额（元）" align="center" prop="amount" />
                                <el-table-column label="服用备注" align="center" prop="notes" />
                                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                                    <template slot-scope="scope">
                                        <el-button size="mini" type="text" icon="el-icon-edit"
                                            @click="handleUpdateP(scope.row)"
                                            v-hasPermi="['his:prescription:edit']">修改</el-button>
                                        <el-button size="mini" type="text" icon="el-icon-delete"
                                            @click="handleDeleteP(scope.row)"
                                            v-hasPermi="['his:prescription:remove']">删除</el-button>
                                    </template>
                                </el-table-column>
                                <!-- <el-table-column label="支付状态" align="center" prop="state">
                                    <template slot-scope="scope">
                                        <dict-tag :options="dict.type.his_prescription_state"
                                            :value="scope.row.state" />
                                    </template>
                                </el-table-column> -->
                            </el-table>
                            <pagination v-show="total > 0" :total="totalP" :page.sync="queryParams.pageNum"
                                :limit.sync="queryParams.pageSize" @pagination="getList" />

                        </el-tab-pane>
                    </el-tabs>
                </el-card>
            </el-col>
        </el-row>

        <!-- 选择挂号患者窗口-->
        <el-dialog title="选择挂号患者" :visible.sync="dialogTableVisible">
            <el-tabs v-model="activeName1" type="card" @tab-click="tabclick">
                <el-tab-pane label="待就诊列表" name="one">
                    <el-table :data="registrationList">
                        <el-table-column label="患者姓名" align="center" prop="patientName" />
                        <el-table-column label="挂号ID" align="center" prop="registrationId" />
                        <el-table-column label="挂号类型" align="center" prop="scheduleType" />
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <el-button size="small" type="success" icon="el-icon-check"
                                    @click="handleUpdate(scope.row)">接诊
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList" />
                </el-tab-pane>
                <el-tab-pane label="就诊中列表" name="weo">
                    <el-table :data="registrationList">
                        <el-table-column label="患者姓名" align="center" prop="patientName" />
                        <el-table-column label="挂号ID" align="center" prop="registrationId" />
                        <el-table-column label="挂号类型" align="center" prop="scheduleType" />
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <el-button size="small" type="success" icon="el-icon-check"
                                    @click="handleUpdate(scope.row)">接诊
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList" />
                </el-tab-pane>
                <el-tab-pane label="就诊完成列表" name="three">
                    <el-table :data="registrationList">
                        <el-table-column label="患者姓名" align="center" prop="patientName" />
                        <el-table-column label="挂号ID" align="center" prop="registrationId" />
                        <el-table-column label="挂号类型" align="center" prop="scheduleType" />
                    </el-table>
                    <pagination v-show="total > 0" :total="total" :page.sync="queryParamsP.pageNum"
                        :limit.sync="queryParamsP.pageSize" @pagination="getPrescription" />
                </el-tab-pane>
            </el-tabs>
        </el-dialog>

        <!-- 添加或修改处方药品对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="病例ID" prop="treatId">
                    <el-input v-model="form.treatId" placeholder="请输入病例id" disabled />
                </el-form-item>
                <el-form-item label="药品名称" prop="medicineId">
                    <el-select v-model="form.medicineId" placeholder="请选择药品" @change="calculateAmount">
                        <el-option v-for="item in medicineList" :key="item.medicineId" :label="item.medicineName"
                            :value="item.medicineId" :disabled="item.stock == 0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="开药数量" prop="quantity">
                    <el-input v-model="form.quantity" placeholder="请输入开药数量" @input="calculateAmount" />
                </el-form-item>
                <el-form-item label="金额" prop="amount">
                    <el-input v-model="form.amount" placeholder="药品总金额" disabled />
                </el-form-item>
                <el-form-item label="服用备注" prop="notes">
                    <el-input v-model="form.notes" placeholder="请输入服用备注" />
                </el-form-item>
                <!-- <el-form-item label="支付状态(0已支付，1未支付，2已退费）" prop="state">
                    <el-input v-model="form.state" placeholder="请输入支付状态(0已支付，1未支付，2已退费）" />
                </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { getPatient, updatePatient } from "@/api/his/patient";
import { listPrescription, getPrescription, delPrescription, addPrescription, updatePrescription } from "@/api/his/prescription";
import {
    getRegistration,
    getRegAndTreat,
    updateRegistration,
} from "@/api/his/registration";
import { listTreat, addTreat, updateTreat, getTreatByRegId } from "@/api/his/treat";
import { listMedicine, getMedicine, delMedicine, addMedicine, updateMedicine } from "@/api/his/medicine";
export default {
    dicts: ["his_treat_contagion"],
    data() {
        return {
            value: "",
            loading: false,
            total: 0,
            dialogTableVisible: false,
            queryParams: {
                pageNum: 1,
                registrationStatus: 1,
            },
            //挂号表，挂号列表表格数据
            registrationList: [],
            //开药单，药品处方表数据
            prescriptionList: [],
            //开药单总条数
            totalP: 0,
            // 是否显示弹出层
            open: false,
            // 弹出层标题
            title: "",
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 开药单弹出框 表单参数
            form: {},
            // 开药单弹出框 表单校验
            rules: {
                medicineId: [
                    { required: true, message: "药品不能为空", trigger: "change" }
                ],
                quantity: [
                    { required: true, message: "药品数量不能为空", trigger: "blur" }
                ],
                // amount: [
                //     { required: true, message: "金额不能为空", trigger: "blur" }
                // ],
                // treatId: [
                //     { required: true, message: "病例id不能为空", trigger: "blur" }
                // ],
                notes: [
                    { required: true, message: "服用备注不能为空", trigger: "blur" }
                ],
                // state: [
                //     { required: true, message: "支付状态(0已支付，1未支付，2已退费）不能为空", trigger: "blur" }
                // ],
            },
            //病例单
            treat: [],
            //开药单查询参数
            queryParamsP: {
                pageNum: 1,
                pageSize: 10,
                treatId: null,
            },
            //患者表单数据
            patientform: {
                patientName: "",
                idCard: "",
                tel: "",
                gender: "",
                patientDate: "",
                age: "",
                address: "",
                allergy: "",
                patientId: "",
            },
            //选中的挂号单
            registration: {
                registrationId: "", //挂号主键
                registrationStatus: "", //挂号状态
                registrationNo: "", //挂号编号
            },
            //就诊表单数据，病例单
            treatform: {
                treatRegistrationId: null,
                treatDate: null,
                treatContagion: null,
                treatComplaint: null,
                treatInfo: null,
                treatAdvice: null,
                remark: null,
                treatNo: null,
            },
            activeName1: "one", //默认显示第一页
            activeName2: "first", //默认显示第一页
            // 药品数据
            medicineList: [],
            // 药品查询参数
            queryParamsM: {
                pageNum: 1,
                pageSize: 10,
                medicineName: null,
                medicineType: null,
                keyword: null,
                prescribe: null,
                factoryId: null,
                status: null,
            },
        };
    },
    created() {
        this.getmedicineList();
    },
    computed: {
        //判断所有药品中，是否有选中的药品
        isSelectedMedicine() {
            return this.form.medicineId !== null;
        },
        selectedMedicine() {
            return this.medicineList.find(item => item.medicineId === this.form.medicineId);
        },
    },
    methods: {
        // 计算开药总金额
        calculateAmount() {
            if (this.selectedMedicine && this.form.quantity > 0) {
                const calculatedAmount = this.form.quantity * this.selectedMedicine.price;
                this.form.amount = calculatedAmount; // 更新form.amount
            } else {
                this.form.amount = 0; // 如果没有有效选择或数量，则重置为0
            }
        },
        // 查询所有药品信息
        getmedicineList() {
            // 查询药品信息
            listMedicine(this.queryParamsM).then(response => {
                this.medicineList = response.rows;
                console.log("所有药品：");
                console.log(this.medicineList);
            });
        },
        // 根据medicineId获取药品名称
        getMedicineName(medicineId) {
            const medicine = this.medicineList.find((item) => item.medicineId === medicineId);
            return medicine ? medicine.medicineName : '未命名药品';
        },
        /**重置页面表单 */
        reset() {
            this.treatform = {
                treatRegistrationId: null,
                treatDate: null,
                treatContagion: null,
                treatComplaint: null,
                treatInfo: null,
                treatAdvice: null,
                remark: null,
                treatNo: null,
            };
            this.patientform = {
                patientName: "",
                idCard: "",
                tel: "",
                gender: "",
                patientDate: "",
                age: "",
                address: "",
                allergy: "",
                patientId: "",
            };
            this.registration = {
                registrationId: "", //挂号主键
                registrationStatus: "", //挂号状态
                registrationNo: "", //挂号编号
            };
            this.treat = [];
            this.queryParamsP = {
                pageNum: 1,
                pageSize: 10,
                treatId: null,
            };
            this.prescriptionList = [];
            this.loading = true;
        },
        /**************************************开药单操作**********************************/
        // 重置添加药方表单
        resetP() {
            this.form = {
                prescriptionId: null,
                medicineId: null,
                quantity: null,
                amount: null,
                treatId: null,
                notes: null,
                state: null,
                delFlag: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null
            };
            this.form.treatId = this.treat.treatId;
            this.resetForm("form");
        },
        /** 新增按钮操作 */
        handleAddP() {
            this.resetP();
            this.open = true;
            this.title = "添加处方药品";
        },
        /** 修改按钮操作 */
        handleUpdateP(row) {
            this.resetP();
            const prescriptionId = row.prescriptionId || this.ids
            getPrescription(prescriptionId).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改处方药品";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.prescriptionId != null) {
                        updatePrescription(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            // 查询开药单信息
                            this.getPrescription();
                        });
                    } else {
                        addPrescription(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            // 查询开药单信息
                            this.getPrescription();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDeleteP(row) {
            const prescriptionIds = row.prescriptionId || this.ids;
            this.$modal.confirm('是否确认删除处方药品编号为"' + prescriptionIds + '"的数据项？').then(function () {
                return delPrescription(prescriptionIds);
            }).then(() => {
                // 查询开药单信息
                this.getPrescription();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExportP() {
            this.download('his/prescription/export', {
                ...this.queryParamsP
            }, `prescription_${new Date().getTime()}.xlsx`)
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.resetP();
        },
        /*************************************************************************************/
        /**查询挂号列表 */
        getList() {
            listTreat(this.queryParams).then((r) => {
                this.registrationList = r.rows;
                console.log("查询条件: ");
                console.log(this.queryParams);
                console.log("查询结果(挂号表): " + r);
                console.log(r);
            });
        },
        //选择患者按钮操作
        checkpatient() {
            this.dialogTableVisible = true;
            console.log("点击选择患者");
            this.getList();
            console.log("所有药品：");
            console.log(this.medicineList);
        },
        /** 接诊按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.dialogTableVisible = false;
            //缓存选中的挂号单内容
            this.registration.registrationId = row.registrationId;
            this.registration.registrationStatus = row.registrationStatus;
            //通过选中的挂号ID，查询挂号单详情
            getRegistration(this.registration.registrationId).then((r1) => {
                //更新选中的挂号单编号
                this.registration.registrationNo = r1.data.registrationNo;

                // 查询开药单信息
                this.getPrescription();

                //当前选泽的是 待就诊患者
                if (r1.code == 200 && this.registration.registrationStatus == 1) {
                    //加载待就诊患者信息
                    this.patientform.patientId = r1.data.registrationPatientId;
                    getPatient(r1.data.registrationPatientId).then((r2) => {
                        if (r2.code == 200) {
                            this.patientform = r2.data;
                        }
                    });
                }
                //当前选择的是 就诊中患者
                else if (r1.code == 200 && this.registration.registrationStatus == 4) {
                    //加载就诊中患者信息
                    this.patientform.patientId = r1.data.registrationPatientId;
                    getPatient(r1.data.registrationPatientId).then((r2) => {
                        if (r2.code == 200) {
                            this.patientform = r2.data;
                            getRegAndTreat(this.registration.registrationId).then((r) => {
                                //加载病例信息
                                if ((r.code = 200)) {
                                    this.treatform = r.data;
                                    console.log("查询结果(病例表): " + r);
                                }
                            });
                        }
                    });
                }

                //当前选择的是 已完成就诊的患者，不需要进行操作
            });
        },
        /**更新患者信息按钮 */
        update() {
            updatePatient(this.patientform).then((r) => {
                if ((r.code = 200)) {
                    this.$modal.msgSuccess("更新成功");
                }
            });
        },
        /**保存病例按钮 */
        add() {
            console.log(this.patientform.patientId);
            if (this.patientform.patientId == "") {
                //无患者信息
                this.$message.error("请选择待就诊患者");
            } else if (this.treatform.treatNo == null) {
                //无病例单号，增加病例
                this.treatform.treatRegistrationId = this.registration.registrationId;
                console.log(this.treatform);
                addTreat(this.treatform).then((r) => {
                    if ((r.code = 200)) {
                        this.treatform.treatNo = r.data;
                        this.$modal.msgSuccess("病历保存成功");
                    }
                });
            } else {
                //有患者信息，有病例单号，修改病例
                updateTreat(this.treatform).then((r) => {
                    if ((r.code = 200)) {
                        this.$modal.msgSuccess("病历更新成功");
                    }
                });
            };
            // 查询开药单信息
            this.getPrescription();
        },
        /**就诊完成按钮 */
        updateReg() {
            this.add();
            this.registration.registrationStatus = 2;
            updateRegistration(this.registration).then((r) => {
                if (r.code == 200) {
                    this.$modal.msgSuccess("就诊完成");
                    this.reset(); //清空
                }
            });
        },
        //选择挂号患者窗口的事件
        tabclick(tab, event) {
            if (tab.index == 0) {
                this.queryParams.registrationStatus = 1;
            } else if (tab.index == 1) {
                this.queryParams.registrationStatus = 4;
            } else {
                this.queryParams.registrationStatus = 2;
            }
            this.getList();
        },
        /** 查询开药单信息 */
        getPrescription() {
            console.log("查询开药单信息");
            /** 根据挂号Id查询就诊（病例）详情 */
            getTreatByRegId(this.registration.registrationId).then(
                (response) => {
                    //获取病例数据
                    this.treat = response.data;
                    console.log("病例数据: ")
                    console.log(this.treat)
                    console.log(this.treatform)

                    //更新开药单查询条件 
                    this.queryParamsP.treatId = this.treat.treatId;
                    /** 根据病例ID 查询 药品处方列表，即开药单 */
                    listPrescription(this.queryParamsP).then((responseP) => {
                        //获取开药单数据
                        this.prescriptionList = responseP.rows;
                        this.totalP = responseP.total;
                        this.loading = false;
                    });
                });
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.prescriptionId)
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        // indexMethod(index) {
        //     return index + 1;
        // },
    },
};
</script>
